<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="电梯名称" prop="elevatorName">
            <el-input v-model="queryParams.elevatorName" clearable placeholder="请输入电梯名称" style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="事件类型" prop="eventType">
            <el-select v-model="queryParams.eventType" clearable placeholder="请输入事件类型" style="width: 240px">
              <el-option v-for="dict in elevator_event_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:elevatorEvent:remove']" :disabled="multiple" icon="Delete" plain type="danger"
                       @click="handleDelete()"
            >删除
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['iot:elevatorEvent:export']">导出</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="elevatorEventList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="事件单号" align="center" prop="eventCode"/>
        <el-table-column label="事件类型" align="center" prop="eventType">
          <template #default="scope">
            <dict-tag :options="elevator_event_type" :value="scope.row.eventType"/>
          </template>
        </el-table-column>
        <el-table-column label="门状态" align="center" prop="doorStatus">
          <template #default="scope">
            <dict-tag :options="elevator_door_status" :value="scope.row.doorStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="电瓶车状态" align="center" prop="motorcycleStatus">
          <template #default="scope">
            <dict-tag :options="electric_vehicle_status" :value="scope.row.motorcycleStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="轿厢人数" align="center" prop="personCount"/>
        <el-table-column label="上报时间" align="center" prop="reportTime" width="180">
        </el-table-column>
        <el-table-column label="平层状态" align="center" prop="levelingStatus">
          <template #default="scope">
            <dict-tag :options="elevator_leveling_status" :value="scope.row.levelingStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="运行速度 cm/s" align="center" prop="runSpeed"/>
        <el-table-column label="气压值 Pa" align="center" prop="airPressure"/>
        <el-table-column label="实际楼层" align="center" prop="currentFloor"/>
        <el-table-column label="楼层名称" align="center" prop="floorName"/>
        <el-table-column label="累计运行次数" align="center" prop="acOperationCount"/>
        <el-table-column label="累计开门次数" align="center" prop="acOpenCount"/>
        <el-table-column label="累计里程 单位米" align="center" prop="acMileage"/>
        <el-table-column label="累计运行时间 秒" align="center" prop="acRunDuration"/>
        <el-table-column label="异常声音" align="center" prop="abnormalSound">
          <template #default="scope">
            <dict-tag :options="electric_vehicle_status" :value="scope.row.abnormalSound"/>
          </template>
        </el-table-column>
        <el-table-column label="急停状态" align="center" prop="emergencyStop">
          <template #default="scope">
            <dict-tag :options="elevator_emergency_status" :value="scope.row.emergencyStop"/>
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" prop="ossId">
          <template #default="scope">
            <ImagePreview
                v-if="scope.row.ossId"
                :height="100"
                :preview-src-list="[scope.row.ossId]"
                :src="scope.row.ossId"
                :width="100"
            />
          </template>
        </el-table-column>
        <el-table-column label="电梯名称" align="center" prop="elevatorName"/>
        <el-table-column label="告警解除时间" align="center" prop="removeTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.removeTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="持续时长(秒)" align="center" prop="eventDuration"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['iot:elevatorEvent:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看电梯画面" placement="top">
              <el-button icon="VideoCamera" link type="primary" @click="viewCamera(scope.row.elevatorId)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList"/>
    </el-card>
    <DevicePlayer ref="devicePlayerRef"/>
  </div>
</template>

<script setup name="ElevatorEvent" lang="ts">
import {
  addElevatorEvent,
  delElevatorEvent,
  getElevatorEvent,
  listElevatorEvent,
  updateElevatorEvent
} from "@/api/iot/elevatorEvent";
import {ElevatorEventForm, ElevatorEventQuery, ElevatorEventVO} from "@/api/iot/elevatorEvent/types";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {startPlay} from "@/api/video_monitor/channel";
import DevicePlayer from '@/views/video_monitor/dialog/devicePlayer.vue'
import {getElevator} from "@/api/iot/elevator";

const devicePlayerRef = ref<InstanceType<typeof DevicePlayer>>();
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {
  electric_vehicle_status,
  elevator_door_status,
  elevator_emergency_status,
  elevator_leveling_status,
  elevator_event_type
} = toRefs<any>(proxy?.useDict("electric_vehicle_status", "elevator_door_status", "elevator_emergency_status", "elevator_leveling_status", "elevator_event_type"));

const elevatorEventList = ref<ElevatorEventVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const elevatorEventFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});

const initFormData: ElevatorEventForm = {
  eventId: undefined,
  elevatorId: undefined,
  eventCode: undefined,
  elevatorName: undefined,
  useUnit: undefined,
  serverUnit: undefined,
  eventType: undefined,
  reportTime: undefined,
  removeTime: undefined,
  eventDuration: undefined,
  remark: undefined
};
const data = reactive<PageData<ElevatorEventForm, ElevatorEventQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elevatorId: undefined,
    eventCode: undefined,
    elevatorName: undefined,
    useUnit: undefined,
    serverUnit: undefined,
    eventType: undefined,
    reportTime: undefined,
    removeTime: undefined,
    eventDuration: undefined,
    params: {}
  },
  rules: {
    eventId: [
      {required: true, message: "事件ID不能为空", trigger: "blur"}
    ],
    elevatorId: [
      {required: true, message: "关联电梯ID不能为空", trigger: "blur"}
    ],
    eventCode: [
      {required: true, message: "事件单号不能为空", trigger: "blur"}
    ],
    elevatorName: [
      {required: true, message: "电梯名称不能为空", trigger: "blur"}
    ],
    useUnit: [
      {required: true, message: "使用单位不能为空", trigger: "blur"}
    ],
    serverUnit: [
      {required: true, message: "维保单位不能为空", trigger: "blur"}
    ],
    eventType: [
      {required: true, message: "事件类型不能为空", trigger: "change"}
    ],
    reportTime: [
      {required: true, message: "上报时间不能为空", trigger: "blur"}
    ],
    removeTime: [
      {required: true, message: "清除时间不能为空", trigger: "blur"}
    ],
    eventDuration: [
      {required: true, message: "事件时长不能为空", trigger: "blur"}
    ],
    remark: [
      {required: true, message: "备注不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询电梯事件列表 */
const getList = async () => {
  loading.value = true;
  const res = await listElevatorEvent(queryParams.value);
  elevatorEventList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  elevatorEventFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ElevatorEventVO[]) => {
  ids.value = selection.map(item => item.eventId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加电梯事件";
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ElevatorEventVO) => {
  reset();
  const _eventId = row?.eventId || ids.value[0];
  const res = await getElevatorEvent(_eventId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改电梯事件";
};

/** 提交按钮 */
const submitForm = () => {
  elevatorEventFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.eventId) {
        await updateElevatorEvent(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addElevatorEvent(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ElevatorEventVO) => {
  const _eventIds = row?.eventId || ids.value;
  await proxy?.$modal.confirm("是否确认删除电梯事件编号为\"" + _eventIds + "\"的数据项？").finally(() => loading.value = false);
  await delElevatorEvent(_eventIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download("iot/elevatorEvent/export", {
    ...queryParams.value
  }, `elevatorEvent_${new Date().getTime()}.xlsx`);
};
/** 查看电梯画面操作 */
const viewCamera = async (elevatorId?: any) => {
  let elevator = await getElevator(elevatorId);
  console.log("查询电梯", elevator.data.numberCode);
  let numberCode = elevator?.data?.numberCode;
  if (numberCode == undefined) {
    proxy?.$modal.msgError("电梯无监控");
    return;
  }
  loading.value = true;
  let strings = numberCode.split("_");
  const deviceId = strings[0];
  const channelId = strings[1];
  const res = await startPlay(deviceId, channelId);
  console.log("devicePlayerRef", devicePlayerRef);
  devicePlayerRef.value?.openDialog("media", deviceId, channelId, {
    streamInfo: res.data,
    hasAudio: true,
  });
  loading.value = false;
};
onMounted(() => {
  getList();
  const elevatorId = proxy?.$route.query.elevatorId;
  if (elevatorId) {
    viewCamera(elevatorId)
  }
});
</script>
